package edu.tsinghua.ddb.components;

import java.util.LinkedList;
import java.util.List;

import edu.tsinghua.ddb.beans.Sqlet;
import edu.tsinghua.ddb.dictionary.Column;

public class SQLParser {
	public static Sqlet parse(String sqlString) {
		Sqlet s = new Sqlet();
		s.setRawSQL(sqlString);

		if (sqlString.startsWith("createdb")) {
			s.setCommand(Sqlet.createdb);
			int beginIndex = sqlString.lastIndexOf(" ")+1;
			String database = sqlString.substring(beginIndex);
			s.setDatabase(database);
		} else if (sqlString.startsWith("createTable")) {
			s.setCommand(Sqlet.createtable);
			int beginIndex = sqlString.indexOf(" ")+1;
			int endIndex = sqlString.indexOf("(");
			String tab = sqlString.substring(beginIndex, endIndex);
			String ids[] = tab.split("::");
			
			s.setDatabase(ids[0].trim());
			s.setTable(ids[1].trim());

			beginIndex = endIndex+1;
			endIndex = sqlString.lastIndexOf(")");
			tab = sqlString.substring(beginIndex, endIndex);
			String cd[] = tab.split(",");
			List<Column> cs = new LinkedList<Column>();
			for(String c : cd){
				String cc[] = c.split(" ");
				cs.add(new Column(cc[0].trim(),cc[1].trim()));
			}
			s.setCreateStmt(cs);
		}
		return s;
	}
}
